﻿/** 
 *Copyright(C) 2018 by #COMPANY# 
 *All rights reserved. 
 *FileName:     #SCRIPTFULLNAME# 
 *Author:       #AUTHOR# 
 *Version:      #VERSION# 
 *UnityVersion：#UNITYVERSION# 
 *Date:         #DATE# 
 *Description:    
 *History: 
 */

using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

// 透明度动画
public class AlphaTween : MonoBehaviour {

    // public.
    public Image thisImage;

    // private.
    // 原透明度
    private float fromAlpha;

    // 至透明度
    private float toAlpha;
    
    // 间隔
    private float duration;

    // 结束回调
    private Action endCallBack;

    // 是否进入动画
    private bool isTween;

    // 经过时间
    private float elapsedTime;

    //-------------------------------------------------------
    // MonoBehaviour Function
    //-------------------------------------------------------
    private void Awake ( ) {
        thisImage = GetComponent<Image> ( );
    }

    // 动画的更新
    private void Update ( ) {
        if (!isTween) {
            return;
        }

        // 经过时间
        elapsedTime += Time.deltaTime;

        if (elapsedTime >= duration) {
            // 动画结束处理
            SetAlpha (toAlpha);
            isTween = false;
            if (endCallBack != null) {
                endCallBack ( );
            }

            Destroy (this);
            return;
        }

        var moveProgress = elapsedTime / duration;
        SetAlpha (Mathf.Lerp (fromAlpha, toAlpha, moveProgress));
    }

    //-------------------------------------------------------
    // Public Function
    //-------------------------------------------------------
    public void DoTween (float fAlpha, float tAlpha, float dur, Action eCallBack) {
        this.fromAlpha = fAlpha;
        this.toAlpha = tAlpha;
        this.duration = dur;
        this.endCallBack = eCallBack;

        SetAlpha (fAlpha);
        elapsedTime = 0;
        isTween = true;
    }

    //-------------------------------------------------------
    // Private Function
    //-------------------------------------------------------
    private void SetAlpha (float alpha) {
        var col = thisImage.color;
        col.a = alpha;
        thisImage.color = col;
    }
}
